/*
 * @lc app=leetcode.cn id=501 lang=typescript
 *
 * [501] 二叉搜索树中的众数
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function findMode(root: TreeNode): number[] {
    let cache = new Map<number, number>();
    findTree(root, cache);
    let count = 0;
    let final: number[] = [];
    for (const [key, val] of cache.entries()) {
        if (val > count) {
            final = [key];
            count = val;
            continue;
        }
        if (val === count) {
            final.push(key);
        }
        console.log(key, val);
    }

    return final;
}
const findTree = (root: TreeNode, cache: Map<number, number>) => {
    cache.set(root.val, (cache.get(root.val) || 0) + 1);
    if (root.left) findTree(root.left, cache);
    if (root.right) findTree(root.right, cache);
};
// @lc code=end
